<template>
  <div class="content-wrapper">
    <div class="content-container">
      <el-form label-width="auto" :inline="true" class="demo-form-inline">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="车辆编码" class="full-width">
              <el-input v-model="filters.vehicleNo" placeholder="请输入车辆编码" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="负责人" class="full-width">
              <el-input v-model="filters.vehiclePerson" placeholder="请输入车辆负责人" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车辆类型" class="full-width">
              <el-input v-model="filters.vehicleType" placeholder="请输入车辆类型" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间" class="full-width" style="margin-right: 0">
              <el-date-picker
                  v-model="filters.createTime"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  class="full-width">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车辆状态" class="full-width">
              <el-select v-model="filters.activeStatus" placeholder="请选择状态" class="full-width">
                <el-option label="全部" :value="null"></el-option>
                <el-option label="可用" :value="true"></el-option>
                <el-option label="不可用" :value="false"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车辆容量" class="full-width">
              <el-input-number
                  v-model="filters.capacity"
                  :min="0"
                  :max="100"
                  controls-position="right"
                  class="full-width">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="right full-width" label=" ">
              <el-button-group class="full-width">
                <el-button icon="search" type="primary" plain @click="search" style="width: 50%">查询</el-button>
                <el-button icon="refresh" @click="resetFilters" style="width: 50%">重置</el-button>
              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="divider"></div>
      <el-row :gutter="20" class="action-buttons">
        <el-col :span="12">
          <el-button type="primary" plain icon="plus" @click="openDialog(null,false)">新建</el-button>
          <el-button type="danger" plain icon="delete" @click="openBatchDeleteDialog">删除</el-button>
        </el-col>
      </el-row>
      <el-table :data="currentTableData"
                style="width: 100%;
              flex: 1"
                :header-cell-style="{
                  backgroundColor: '#f5f7fa',
                  color: '#333',
                  fontWeight: 'bold',
                  textAlign: 'center',
                  padding: '10px 0'
                }"
                :cell-style="{
                  padding: '10px 0'
                }"
                @selection-change="handleSelectionChange"
                :default-sort="{ prop: 'generatedDate', order: 'descending' }">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="车辆编码" width="100">
          <template v-slot="{ row }">
            <el-link type="primary" @click="details = row">{{ row.vehicleNo }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="vehicleType" label="类型" width="80" ></el-table-column>
        <el-table-column prop="vehiclePerson" label="负责人" width="80"></el-table-column>
        <el-table-column prop="driver.driverPhone" label="联系方式" width="150"></el-table-column>
        <el-table-column prop="activeStatus" label="状态" width="100" align="center">
          <template v-slot="scope">
            <el-tag
                :type="scope.row.activeStatus ? 'success' : 'danger'"
                disable-transitions
            >{{ scope.row.activeStatus ? '可用' : '不可用' }}
            </el-tag
            >
          </template>
        </el-table-column>
        <el-table-column prop="temperatureRange" label="温控范围" width="130">
          <template v-slot="scope">
          <span>
            {{
              scope.row.temperatureNeed ? `${scope.row.temperatureLow} ~ ${scope.row.temperatureHigh} ${scope.row.temperatureUnit}` : '不提供'
            }}
          </span>
          </template>
        </el-table-column>
        <el-table-column prop="humidityRange" label="湿控范围" width="130">
          <template v-slot="scope">
          <span>
            {{
              scope.row.humidityNeed ? `${scope.row.humidityLow} ~ ${scope.row.humidityHigh} ${scope.row.humidityUnit}` : '不提供'
            }}
          </span>
          </template>
        </el-table-column>
        <el-table-column prop="capacity" label="容量" width="80" align="right"></el-table-column>
        <el-table-column prop="generatedDate" label="创建时间" sortable width="180">
          <template v-slot="scope">
            <span>{{ formatDate(scope.row.generatedDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template v-slot="scope">
            <el-button @click="openDialog(scope.row,true)" type="text" icon="EditPen" style="font-size: 13px">编辑
            </el-button>
            <el-popconfirm
                width="200"
                confirm-button-text="确认"
                cancel-button-text="取消"
                icon-color="#626AEF"
                title="是否确定删除？"
                @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button type="text" size="small" icon="delete" style="font-size: 13px">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          v-model:current-page="currentPage"
          @current-change="handleCurrentChange"
          class="fixed-pagination">
      </el-pagination>

    </div>
  </div>


  <NewVehicleDialog
      v-model="dialogVisible"
      @update:visible="dialogVisible = $event"
      :data="selectedVehicle"
      :isEdit="isEdit"
      @save="handleSave"
      visible/>

  <!-- 批量删除弹框 -->
  <el-dialog
      title="删除车辆"
      align-center
      v-model="batchDeleteVisible"
      width="60%"
      style="border-radius: 12px;
      display: flex;
      flex-direction: column;
      margin: 0 !important;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      max-height: calc(100% - 30px);
      max-width: calc(100% - 30px);
      justify-content: center;"
  >
    <el-table
        :data="selectedVehicles"
        style="width: 100%;
        margin-bottom: 40px;
        margin-top: 20px;"
        stripe
        border
    >
      <el-table-column prop="vehicleNo" label="车辆编码" width="170px"></el-table-column>
      <el-table-column prop="vehiclePerson" label="负责人" width="160px"></el-table-column>
      <el-table-column prop="vehicleType" label="车辆类型" width="160px"></el-table-column>
      <el-table-column prop="capacity" label="容量" width="160px"></el-table-column>
      <el-table-column prop="activeStatus" label="状态" width="160px">
        <template v-slot="scope">
          <el-tag
              :type="scope.row.activeStatus ? 'success' : 'danger'"
          >{{ scope.row.activeStatus ? '可用' : '不可用' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button @click="batchDeleteVisible = false" type="primary" plain>取消</el-button>
      <el-button type="danger" @click="handleBatchDelete" plain>确定删除</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage} from "element-plus";
import {listVehicle, addVehicle, updateVehicle, deleteVehicle, deleteVehicles} from '@/api/delivery/car.js'; // 引入后端接口封装
import NewVehicleDialog from "@/views/delivery/car/NewVehicleDialog.vue"; // 引入新建/编辑对话框组件

export default {
  components: {NewVehicleDialog},
  setup() {
    // 定义筛选条件
    const filters = reactive({
      vehicleNo: '', // 车辆编码
      vehiclePerson: '', // 负责人
      vehicleType: '', // 车辆类型
      createTime: [], // 创建时间范围
      activeStatus: null, // 车辆状态
      capacity: null, // 车辆容量
    });

    // 定义对话框相关变量
    const dialogVisible = ref(false); // 控制 Dialog 显示
    const selectedVehicle = ref({}); // 存储当前选中的车辆信息
    const isEdit = ref(false); // 区分新建(false) 和编辑(true)

    // 定义表格数据和分页相关变量
    const currentTableData = ref([]); // 表格数据
    const total = ref(0); // 总记录数
    const pageSize = ref(8); // 每页条数
    const currentPage = ref(1); // 当前页码
    // 打开弹窗
    const openDialog = (vehicle, edit) => {
      dialogVisible.value = true;
      isEdit.value = edit;
      selectedVehicle.value = vehicle || {};
      console.log(selectedVehicle.value);
    };
    // 保存逻辑
    const handleSave = async (vehicleData) => {
      try {
        if (isEdit.value) {
          // 编辑模式
          await updateVehicle(vehicleData);
        } else {
          // 新建模式
          await addVehicle(vehicleData);
        }
        dialogVisible.value = false; // 关闭弹窗
        search(); // 刷新列表
      } catch (error) {
        console.error('保存失败:', error);
      }
    };

    //批量删除
    const rowKey = (row) => row.vehicleNo; // 表格行的唯一标识
    const selectedVehicles = ref([]); // 存储选中的车辆信息
    const batchDeleteVisible = ref(false); // 控制批量删除弹框显示

    // 打开批量删除弹框
    const openBatchDeleteDialog = () => {
      if (selectedVehicles.value.length === 0) {
        return ElMessage.warning("请先选择车辆！");
      }
      batchDeleteVisible.value = true;
    };

    // 批量删除
    const handleBatchDelete = async () => {
      if (batchSelectedVehicles.value.length === 0) {
        return ElMessage.warning("请选择要删除的车辆！");
      }
      const vehicleNos = selectedVehicles.value.map((item) => item.vehicleNo); // 获取选中车辆的车辆编码
      console.log(vehicleNos);
      try {
        await deleteVehicles(vehicleNos); // 调用批量删除接口
        ElMessage.success("批量删除成功！");
        batchDeleteVisible.value = false; // 关闭弹框
        search(); // 刷新表格数据
      } catch (error) {
        console.error("批量删除失败：", error);
      }
    };

    // 表格主选择框选中时触发
    const handleSelectionChange = (rows) => {
      selectedVehicles.value = rows;
    };

    // 格式化日期（保留年月日）
    const formatDate = (value) => {
      if (!value) return '';
      const date = new Date(value);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    // 查询车辆列表
    const search = async () => {
      const query = {
        vehicleNo: filters.vehicleNo,
        vehiclePerson: filters.vehiclePerson,
        vehicleType: filters.vehicleType,
        startDate: filters.createTime.length ? formatDate(filters.createTime[0]) : null,
        endDate: filters.createTime.length ? formatDate(filters.createTime[1]) : null,
        activeStatus: filters.activeStatus,
        capacity: filters.capacity,
        page: currentPage.value,
        pageSize: pageSize.value,
      };
      try {
        const response = await listVehicle(query);
        currentTableData.value = response.data;
        total.value = response.total;
      } catch (error) {
        console.error('获取车辆信息失败:', error);
      }
    };

    // 重置筛选条件
    const resetFilters = () => {
      filters.vehicleNo = '';
      filters.vehiclePerson = '';
      filters.vehicleType = '';
      filters.createTime = [];
      filters.activeStatus = null;
      filters.capacity = null;
      currentPage.value = 1;
      search();
    };

    // 处理分页切换
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      search();
    };

    // 删除单条记录
    const handleDelete = async (row) => {
      try {
        await deleteVehicle(row.vehicleNo); // 调用删除接口
        if (currentTableData.value.length === 1 && currentPage.value > 1) {
          // 如果当前页只剩最后一条数据且当前页码大于1
          currentPage.value -= 1; // 自动跳转到上一页
        }

        search(); // 调用 search 方法重新拉取数据
      } catch (error) {
        console.error('删除失败:', error);
      }
    };

    // 导出数据
    const exportData = () => {

    };

    // 初始化数据
    onMounted(() => {
      search();
    });

    return {
      filters,
      currentTableData,
      total,
      pageSize,
      currentPage,
      formatDate,
      search,
      resetFilters,
      handleCurrentChange,
      openDialog,
      handleDelete,
      exportData,
      dialogVisible,
      selectedVehicle,
      isEdit,
      handleSave,
      selectedVehicles,
      batchDeleteVisible,
      openBatchDeleteDialog,
      handleBatchDelete,
      handleSelectionChange,
      rowKey,
    };
  },
};
</script>


<style scoped>
.el-container {
  height: 100%;
  width: 100%;
}

.content-wrapper {
  background-color: #f5f7fa;
  min-height: inherit;
  display: flex;
  height: calc(100vh - 84px);
  width: 100%;
}


.content-container {
  background-color: white;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  width: calc(100% - 40px);
  height: calc(100% - 30px);
  box-sizing: border-box;
  border-radius: 8px;
  position: relative;
  display: flex;
  flex-direction: column;
  margin-left: 20px;
  margin-top: 15px;
}

.divider {
  height: 1px;
  background-color: #eaeaea;
  margin-top: 0;
  margin-bottom: 12px;
}

.dialog-footer {
  text-align: center; /* 按钮居中 */
}

.action-buttons {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.right-aligned {
  display: flex;
  justify-content: flex-end;
}

.el-segmented {
  width: 100%;
}

.el-form-item.right:deep(.el-form-item__content) {
  justify-content: end;
}

.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  background: white;
}

.full-width {
  width: 100%;
}

.fixed-pagination {
  position: relative;
  right: 0;
  align-self: end;
  margin-top: 20px;
}
</style>
